# -*- coding: utf-8 -*-
import hashlib
import json

from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.ip_address import get_ip_address

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '0000000691': {
        'API_KEY': '98f8442fed195ccad6b9a1ce78040292'
    },
    '0000000746': {
        'API_KEY': '02e17b93e3e36fdf239c62b14af78d9b'
    }
}

SDK_CONF = {
    'ios_v_1_0': 'ios_v1_0_3',  # 我们的支付sdk版本: 明天云的支付sdk版本
    'android_v_1_0': 'android_v1_0_11'
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if parameter[k] != "":
            s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % key
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    _LOGGER.info(u'origin string: %s' % s)
    sign = m.hexdigest()
    return sign


def create_charge(pay, pay_amount, info):
    charge_resp = {}
    sdk_version = SDK_CONF[info['sdk_version']]
    app_id = info['app_id']
    channel = info['channel']
    body = info['body']
    parameter_dict = {
        'version': sdk_version,
        'amount': int(pay_amount * 100),
        'appid': app_id,
        'body': body,
        'payChannelId': channel,
        'mchntOrderNo': pay.id,
        'notifyUrl': '{}/pay/api/{}/mingtianyun/'.format(
            settings.NOTIFY_PREFIX, settings.NOTIFY_PATH),
        'subject': u'商品',
        'clientIp': get_ip_address('enp2s0')
    }
    sign = generate_sign(parameter_dict, _get_api_key(app_id))
    parameter_dict['signature'] = sign
    charge_resp.update({
        'charge_info': parameter_dict,
    })
    _LOGGER.info("mintianyun data after charge: %s", charge_resp)
    return charge_resp


def check_notify_sign(request):
    data = json.loads(request.body)
    sign = data.pop('signature')
    app_id = data['appid']
    api_key = _get_api_key(app_id)
    calculated_sign = generate_sign(data, api_key)
    if sign.lower() != calculated_sign:
        _LOGGER.info("mingtianyun sign: %s, calculated sign: %", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % data)
    pay_id = data['mchntOrderNo']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('mingtianyun event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    trade_status = int(data['paySt'])
    mch_id = pay.mch_id
    trade_no = data['orderNo']
    total_fee = float(data['amount']) / 100

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == 2:
        _LOGGER.info('mingtianyun check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    pass
